package com.rao.service;

import com.rao.core.utils.HttpRequestUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationDetailsSource;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Component
@Slf4j
public class LoginService {

    @Autowired
    AuthenticationManager authenticationManager;

    protected AuthenticationDetailsSource<HttpServletRequest, ?> authenticationDetailsSource = new WebAuthenticationDetailsSource();

    /**
     * 登录
     * 截肢security的源代码 UsernamePasswordAuthenticationFilter
     *
     * @param username
     * @param password
     * @return
     */
    public String login(String username, String password) {
        UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password);
        Authentication authenticate = null;
        try {
            authRequest.setDetails(this.authenticationDetailsSource.buildDetails(HttpRequestUtil.httpServletRequest()));
            authenticate = authenticationManager.authenticate(authRequest);
            SecurityContextHolder.getContext().setAuthentication(authenticate);
        } catch (AuthenticationException e) {
            log.error(e.getMessage());
            throw e;
        }
        //角色权限
        return "认证与授权成功";
    }
}
